package com.ruoyi.aitapp.utils;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterJob;
import java.io.File;

public class PrintUtils {
    /**
     * 打印PDF文件
     * @param filePath 文件路径
     * @param printerName 打印机名称
     */
    public static void printPDF(String filePath,String printerName) throws Exception {
//        String filePath = "path/to/your/pdf-file.pdf"; // 替换为你的PDF文件路径
//        String printerName = "Your Printer Name"; // 替换为你想要使用的打印机名称

        PDDocument document = PDDocument.load(new File(filePath));
        PrinterJob job = PrinterJob.getPrinterJob();
        job.setPageable(new PDFPageable(document));

        // 设置纸张大小（这里以A4为例）
        PageFormat pageFormat = job.defaultPage();
        Paper paper = new Paper();
        paper.setSize(595, 842); // A4 size in points (72 DPI)
        paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight()); // 设置可打印区域
        pageFormat.setPaper(paper);
        // 注意：我们不需要调用job.getPageable()，而是直接设置了pageable
        // job.setPrintable(job.getPageable(), pageFormat); 这行代码是不正确的

        PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
        PrintService targetPrinter = null;
        for (PrintService service : printServices) {
            if (service.getName().equalsIgnoreCase(printerName)) {
                targetPrinter = service;
                break;
            }
        }

        if (targetPrinter != null) {
            job.setPrintService(targetPrinter);
            job.print(); // 直接打印而不显示对话框
            //System.out.println("PDF 已成功发送到打印机：" + targetPrinter.getName());
        } else {
//                System.out.println("未找到名称为 '" + printerName + "' 的打印机");
            throw new Exception("未找到名称为 '" + printerName + "' 的打印机");
        }
    }
}
